package arsmodeller.part;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;

import arsmodeller.editpolicies.ObjectProcessDiagramXYLayoutPolicy;
import arsmodeller.model.ObjectProcessDiagram;
import arsmodeller.model.ObjectProcessingDiagram;
import arsmodeller.model.Thing;

public class ObjectProcessDiagramEditPart extends AbstractGraphicalEditPart {
	private ObjectProcessDiagramAdapter adapter;

	public ObjectProcessDiagramEditPart() {
		super();
		adapter = new ObjectProcessDiagramAdapter();
	}

	@Override
	protected IFigure createFigure() {
		FreeformLayer layer = new FreeformLayer();
		layer.setLayoutManager(new FreeformLayout());
		layer.setBorder(new LineBorder(1));
		return layer;
	}

	@Override
	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.LAYOUT_ROLE,
				new ObjectProcessDiagramXYLayoutPolicy());
	}

	@Override
	protected List<Thing> getModelChildren() {
		List<Thing> retVal = new ArrayList<Thing>();
		ObjectProcessingDiagram opd = (ObjectProcessingDiagram) getModel();
		retVal.addAll(opd.getThings());
		return retVal;
	}

	@Override
	public void activate() {
		if (!isActive()) {
			((ObjectProcessDiagram) getModel()).eAdapters().add(adapter);
		}
		super.activate();
	}

	@Override
	public void deactivate() {
		if (isActive()) {
			((ObjectProcessDiagram) getModel()).eAdapters().remove(adapter);
		}
		super.deactivate();
	}

	public class ObjectProcessDiagramAdapter implements Adapter {

		@Override
		public void notifyChanged(Notification notification) {
			refreshChildren();
		}

		@Override
		public Notifier getTarget() {
			return (ObjectProcessingDiagram) getModel();
		}

		@Override
		public void setTarget(Notifier newTarget) {
			// Do nothing.
		}

		@Override
		public boolean isAdapterForType(Object type) {
			return type.equals(ObjectProcessingDiagram.class);
		}
	}
}
